package com.api.controller;

import com.api.mapper.TaskMapper;
import com.api.mapper.UserTaskMapper;
import com.api.pojo.Task;
import com.api.pojo.UserTask;
import com.api.utils.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ut")
public class UserTaskController {

    @Autowired
    UserTaskMapper utm;

    @Autowired
    TaskMapper tm;

    @RequestMapping("/get")
    public Map<String, Object> get(Integer uid, Integer state, Integer pageNo, Integer pageSize) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        List<Task> tasks = utm.getTask(uid);
        tasks.forEach(e -> {
            try {
                if (Time.getNowTime() > Time.strToTime(e.getEt())) {
                    UserTask userTask = new UserTask();
                    userTask.setId(e.getId());
                    userTask.setState(3);
                    utm.update(userTask);
                }
            } catch (ParseException ex) {
                throw new RuntimeException(ex);
            }
        });

        pageNo = --pageNo * pageSize;
        List<UserTask> list = utm.get(uid, state, pageNo, pageSize);
        list.forEach(e -> {
            e.setTask(tm.getById(e.getTid()));
        });
        map.put("data", list);
        map.put("total", utm.countPage(uid, state));
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }
    
    @RequestMapping("/clock")
    public Map<String, Object> clock(UserTask userTask) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        utm.update(userTask);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }
}
